package com.lukebang.service.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import com.lukebang.constant.Const;
import com.lukebang.dao.CityCostRuleDAO;
import com.lukebang.dao.CustomerAddressDAO;
import com.lukebang.dao.MerchantDAO;
import com.lukebang.dao.MerchantsWalletRecordDAO;
import com.lukebang.dao.RepairIndentDAO;
import com.lukebang.dao.TerritoryDAO;
import com.lukebang.dao.WorkerDao;
import com.lukebang.dao.WorkerWalletRecordDao;
import com.lukebang.pojo.CityCostRule;
import com.lukebang.pojo.CustomerAddress;
import com.lukebang.pojo.Indent;
import com.lukebang.pojo.Merchant;
import com.lukebang.pojo.RepairIndent;
import com.lukebang.service.IRepairIndentService;
import com.lukebang.util.DateUtils;
import com.lukebang.util.JsonUtil;
import com.lukebang.util.ClothCurtain.Arith;

/**
 * 
 * RepairIndentServiceImpl 上午11:16:30
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */
@Service("repairIndentSER")
public class RepairIndentServiceImpl implements IRepairIndentService {
	private static Logger logger = LogManager.getLogger(RepairIndentServiceImpl.class.getName());
	@Resource
	CustomerAddressDAO customerAddressDAO;
	@Resource
	TerritoryDAO territoryDAO;
	@Resource
	RepairIndentDAO repairIndentDAO;
	@Resource
	CityCostRuleDAO cityCostRuleDAO;
	@Resource
	private MerchantsWalletRecordDAO merchantsWalletRecordDAO;
	@Resource
	private MerchantDAO  merchantDAO;
	@Resource
	private WorkerDao workerDao;
	@Resource
	private WorkerWalletRecordDao workerWalletRecordDao;


	@Override
	public Map<String, Object> selectRepairIndentByMerchant(HttpSession session, String customerName,
			String customerPhone, String indentID, String subscribeTimeBegin, String subscribeTimeEnd,
			String beginTimeBegin, String beginTimeEnd, Integer indentStatus, Integer offset, Integer limit,
			String sort, String order) {

		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		Map<String, Object> retsMap = new HashMap<String, Object>();
		retsMap.put("total", 0);
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("offset", offset);
		queryMap.put("limit", limit);
		queryMap.put("sort", sort);
		queryMap.put("order", order);
		queryMap.put("customerName", customerName);
		queryMap.put("customerPhone", customerPhone);
		queryMap.put("indentID", indentID);
		queryMap.put("subscribeTimeBegin", subscribeTimeBegin);
		queryMap.put("subscribeTimeEnd", subscribeTimeEnd);
		queryMap.put("beginTimeBegin", beginTimeBegin);
		queryMap.put("beginTimeEnd", beginTimeEnd);
		queryMap.put("indentStatus", indentStatus);
		queryMap.put("merchantID", merchant.getMerchantsId());
		List<Indent> beans = repairIndentDAO.selectRepairIndentByMerchant(queryMap);
		retsMap.put("total", repairIndentDAO.selectRepairIndentCountByMerchant(queryMap));
		retsMap.put("rows", beans);
		return retsMap;
	}

	@Override
	public Integer insertRepairIndent(HttpServletRequest request, String phone, String name, String weiXbody,
			String detailAddress, String province, String city, String country, String orderTime,
			Integer isNeedTakeGoods, String pickupPhone, String pickupProvince, String pickupCity, String pickupCountry,
			String pickAddress, HttpSession session) {
		// 得到登陆的商户的信息
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		// 根据传送过来的code 转化成对应的省和市和城镇
		List<String> areaNames = territoryDAO.selectForConvertCodeToAreaName(province, city, country);
		// ====================先为用户添加一个订单地址
		CustomerAddress customerAddress = new CustomerAddress();
		customerAddress.setAddress(detailAddress);
		customerAddress.setProvince(areaNames.get(0));
		customerAddress.setCity(areaNames.get(1));
		customerAddress.setArea(areaNames.get(2));
		customerAddress.setAreaCode(country);
		customerAddress.setName(name);
		customerAddress.setPhone(phone);
		customerAddress.setCuAddressCodeStr(province + "/" + city);
		customerAddressDAO.insertCustomerAddress(customerAddress);
		logger.debug("插入地址的ID是：{}", customerAddress.getCuAdId());
		// ====================正式插入订单信息
		RepairIndent indent = new RepairIndent();
		// '订单类型0测量 1安装 2维修 3经销商自主测量的',
		indent.setType(2);
		indent.setStatus(4);
		// 是谁下的订单
		indent.setCustomerId(merchant.getMerchantsId());
		// 订单产生时间
		indent.setBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		// 订单预约的时间
		indent.setSubscribeTime(orderTime);
		// 代表是商家或者个人下的订单 有利于后面的统计
		indent.setIndentType(3);
		indent.setCuAdId(customerAddress.getCuAdId());
		indent.setCustomerId(merchant.getMerchantsId());
		/**
		 * 查询出商人和工人不同的订花费规则
		 */
		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO.selectCostRuleByCityCode(province + "/" + city, 0);
		CityCostRule cityCostRuleForWorker = cityCostRuleDAO.selectCostRuleByCityCode(province + "/" + city, 1);
		logger.debug(JsonUtil.toJson(cityCostRuleForMerchant));
		logger.debug(JsonUtil.toJson(cityCostRuleForWorker));
		Double merchantsPrice = (Double) cityCostRuleForMerchant.getRepairStartingFare();
		Double indentPrice = (Double) cityCostRuleForWorker.getRepairStartingFare();
		if (isNeedTakeGoods == 1) {
			// 设置取货地址
			List<String> pickupAreaNames = territoryDAO.selectForConvertCodeToAreaName(province, city, country);
			indent.setBaseAddress(pickupAreaNames.get(0) + pickupAreaNames.get(1) + pickupAreaNames.get(2));
			indent.setDetailAddress(pickAddress);
			indent.setTakeGoodsTel(pickupPhone);
			merchantsPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), merchantsPrice);
			indentPrice = Arith.add((Double) cityCostRuleForWorker.getTakeGoodsPrice(), indentPrice);
		}
		indent.setWeiXbody(weiXbody);
		indent.setIsNeedTakeGoods(isNeedTakeGoods);
		indent.setIndentPrice(indentPrice);
		indent.setMerchantsPrice(merchantsPrice);
		indent.setMerchantsRealPrice(merchantsPrice);
		indent.setWorkerRealPrice(indentPrice);
		indent.setIndentSource(1);
		repairIndentDAO.insertRepairIndent(indent);
		return indent.getIndentId();
	}

//	/**
//	 * 
//	 * @param indentID
//	 *            根据订单的ID进行系统的支付
//	 * @return
//	 */
//	public boolean modifyForPayRepairIndent(HttpServletRequest request, Integer indentID, Double addPrice,
//			Integer relievedBao, Integer crampetNumber, Integer fourClawNumber, Integer motorNumber,
//			HttpSession session) {
//		logger.debug("需要付款的订单ID是：{}，加价费用是：{}，安心保选择：{}", indentID, addPrice, relievedBao);
//		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
//		RepairIndent repairIndent = (RepairIndent) repairIndentDAO.selectByPrimaryKey(indentID);
//		/**
//		 * 查询出商人和工人不同的订花费规则
//		 */
//		CustomerAddress customerAddress = customerAddressDAO.selectCustomerAddressByIndent(indentID);
//		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO
//				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 0);
//		CityCostRule cityCostRuleForWorker = cityCostRuleDAO
//				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 1);
//		logger.debug(JsonUtil.toJson(cityCostRuleForMerchant));
//		logger.debug(JsonUtil.toJson(cityCostRuleForWorker));
//		// 计算商家和工人对应的配件价格
//		Double accessoryPriceForMerchant = cityCostRuleForMerchant.getCrampetPrice() * crampetNumber
//				+ cityCostRuleForMerchant.getFourClawPrice() * fourClawNumber
//				+ cityCostRuleForMerchant.getMotorPrice() * motorNumber;
//		Double accessoryPriceForWorker = cityCostRuleForWorker.getCrampetPrice() * crampetNumber
//				+ cityCostRuleForWorker.getFourClawPrice() * fourClawNumber
//				+ cityCostRuleForWorker.getMotorPrice() * motorNumber;
//		logger.debug("商家配件合计：{}", accessoryPriceForMerchant);
//		logger.debug("工人配件合计：{}", accessoryPriceForWorker);
//
//		Double needPayMoney = repairIndent.getMerchantsPrice() + addPrice + accessoryPriceForMerchant;
//		if (relievedBao == null) {
//			relievedBao = 0;
//		}
//		if (relievedBao == 1) {
//			needPayMoney = needPayMoney + 5;
//		}
//		logger.error("+++++++++++++++++++++++需要维修订单付款的总价格：{}++++++++++++++++++++++++++++", needPayMoney);
//		String lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
//				PayMethod.ALIPAY.getIndex(), TypeOfIndent.MEASURE.getIndex());
//		request.setAttribute("lukebang_total_fee", String.valueOf(needPayMoney));
//		request.setAttribute("lukebang_body", "维修订单付款");
//		request.setAttribute("lukebang_tradeno", lukebang_order_num);
//		request.setAttribute("lukebang_subject", "维修订单");
//		request.setAttribute("lukebang_returnUrl", "http://lukebang.com.cn/lukebang/indent/addRepair.htm");
//		Map<String, String> extraMap = new HashMap<String, String>();
//		extraMap.put("bussType", String.valueOf(TypeOfIndent.REPAIR.getName()));
//		extraMap.put("indent", String.valueOf(indentID));
//		extraMap.put("relievedBao", String.valueOf(relievedBao));
//		extraMap.put("addPrice", String.valueOf(addPrice));
//		extraMap.put("originalMerchantPrice", String.valueOf(repairIndent.getMerchantsPrice()));
//		extraMap.put("originalIndentPrice", String.valueOf(repairIndent.getIndentPrice()));
//		extraMap.put("crampetNumber", String.valueOf(crampetNumber));
//		extraMap.put("fourClawNumber", String.valueOf(fourClawNumber));
//		extraMap.put("motorNumber", String.valueOf(motorNumber));
//		extraMap.put("merchantAccessoryPrice", String.valueOf(accessoryPriceForMerchant));
//		extraMap.put("indentAccessoryPrice", String.valueOf(accessoryPriceForWorker));
//		request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
//		/**
//		 * 添加钱包的日志记录 添加钱包的日志记录 添加钱包的日志记录
//		 */
//		MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
//		merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
//		merchantsWalletRecord.setIndentId(indentID);
//		merchantsWalletRecord.setOrderNo(lukebang_order_num);
//		merchantsWalletRecord.setMainMoney(needPayMoney);
//		merchantsWalletRecord.setAddMoney(addPrice);
//		merchantsWalletRecord.setType(3);
//		merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//		merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
//		return false;
//	}

//	@Override
//	public Map<String, Object> quitIndent(HttpServletRequest request, HttpSession session, Integer type,
//			Integer repairIndentId) {
//		// TODO Auto-generated method stub
//		Map<String,Object> map=new HashMap<>();
//		// 1.获取测量单信息
//		RepairIndent indent=repairIndentDAO.selectByPrimaryKey(repairIndentId);
//		if(indent==null){
//			map.put("status", "1");
//			map.put("message", "订单不存在 ...");
//			return map;
//		}
//		// 扣款金额
//		Double subMoney = 0.0;
//		//给予工人的补助
//		Double toWorker=0.0;
//		//商家的钱包
//		Double toMerchant=0.0;
//		
//		//1.所有交易记录
//				Double totalFee=0.0;
//				Map<String,Object> param=new HashMap<>();
//				param.put("indentId", repairIndentId);//测量单号
//				param.put("merchantsType", 0);//交易人身份--商家
//				param.put("merchantsId", indent.getCustomerId());//交易人id
//				param.put("status", 1);//交易状态
//				
//				List<MerchantsWalletRecord> recordList=merchantsWalletRecordDAO.selectMerchantWalletRecords(param);
//				for(MerchantsWalletRecord record:recordList){
//					totalFee+=record.getFinalLostMoney();
//				}
//				if(totalFee >0){
//					//2.处罚规则
//					Map<String, Double> punishMap = cityCostRuleDAO.selectRules(repairIndentId);
//					//商家信息
//					Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
//					
//					switch (indent.getStatus()) {
//						case 0:  //等待工人接单---取消订单,并退还全款
//								toMerchant=totalFee;
//							break;
//						case 1:  //已接单---取消订单，并罚款
//							if(punishMap !=null){
//								subMoney = punishMap.get("punishWorker");//处罚的钱
//								toMerchant = Arith.sub(totalFee, subMoney);//退还给商家的钱
//								toWorker =  punishMap.get("punishWorker");// 补给工人对的钱
//							}
//							break;	
//						case 5: 	//工人已出发--取消订单，并罚款
//							if(punishMap !=null){
//								subMoney = punishMap.get("punishClient");
//								toMerchant = Arith.sub(totalFee, subMoney);
//								toWorker = punishMap.get("punishClient");
//							}
//							break;	
//						case 4:   //未付款---取消订单就Ok
//						case 2: 	//已完成  --取消订单就ok
//							break;	
//						default:  
//							System.out.println("其他状态的测量单暂不支持取消功能 ...  ...");
//							break;
//					}
//					if(toMerchant !=0.0){
//						if(merchant != null){
//							Map<String,Object>paras=new HashMap<>();
//							paras.put("merchantsId", merchant.getMerchantsId());
//							paras.put("wallet", toMerchant+merchant.getWallet());
//							merchantDAO.updateMerchantWallet(paras);
//						}
//						//做交易记录
//						MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
//						merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
//						merchantsWalletRecord.setIndentId(repairIndentId);
//						merchantsWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
//								PayMethod.BALABCEPAY.getIndex(), TypeOfIndent.MEASURE.getIndex()));
//						merchantsWalletRecord.setType(TypeOfIndent.MEASURE.getIndex());
//						merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//						merchantsWalletRecord.setSubMoney(subMoney);
//						merchantsWalletRecord.setFinalLostMoney(subMoney);//罚款金额
//						merchantsWalletRecord.setFinalGetMoney(toMerchant);//退还金额
//						merchantsWalletRecord.setStatus(1);
//						merchantsWalletRecord.setRemark("商家取消订单，违约罚款金额");
//						merchantsWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
//						merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
//					}
//					if(toWorker !=0.0){
//						Worker worker = workerDao.selectWorker(indent.getWorkerId());
//						if(worker !=null){
//							Map<String,Object>paras=new HashMap<>();
//							paras.put("workerId", worker.getWorkerId());
//							paras.put("wallet", toWorker+worker.getWallet());
//							workerDao.updateWalletComple(paras);	
//						}
//						//做交易记录
//						WorkerWalletRecord workerWalletRecord=new WorkerWalletRecord();
//						workerWalletRecord.setWorkerId(worker.getWorkerId());
//						workerWalletRecord.setIndentId(repairIndentId);
//						workerWalletRecord.setFinalGetMoney(toWorker);
//						workerWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(worker.getWorkerId(),
//								PayMethod.BALABCEPAY.getIndex(), TypeOfIndent.MEASURE.getIndex()));
//						workerWalletRecord.setType(8);
//						workerWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//						workerWalletRecord.setStatus(1);
//						workerWalletRecord.setRemark("商家取消订单，工人获取补助");
//						workerWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
//						workerWalletRecordDao.insertWorkerWalletRecord(workerWalletRecord);
//					}
//					//修改订单状态
//					indent.setIsDelete(1);
//					repairIndentDAO.modifyByPrimaryKey(indent);
//					map.put("status", "0");
//					map.put("message", "订单取消成功... ");
//					return map;
//				}
//				map.put("status", "2");
//				map.put("message", "订单取消失败... ");
//				return map;
//	}
}
